package service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

import util.Java_JDBC;

import config.Config;

public class ServerThread implements Runnable {

	private Socket socket;
	private Java_JDBC java_JDBC;
	private BufferedReader reader;
	private PrintWriter writer;

	public ServerThread(Socket socket,Java_JDBC java_JDBC) {
		this.socket = socket;
		this.java_JDBC = java_JDBC;
	}

	@Override
	public void run() {
		try {
			System.out.println("客户端连接成功IP: " + socket.getInetAddress());
			InputStream inputStream = socket.getInputStream();
			reader = new BufferedReader(new InputStreamReader(inputStream));
			OutputStream outputStream = socket.getOutputStream();
			writer = new PrintWriter(outputStream, true);
			String str = reader.readLine();
			System.out.println("str的值：-----》"+str);
			if (str!=null) {
				String infor[] = str.split(",");
				System.out.println("收到了：" + infor[0] + infor[1] + infor[2]);
				handlerInformation(infor);
			}
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				if (socket != null) {
					socket.close();
				}
			} catch (IOException e1) {
			}
		} 
	}

	/**
	 * 处理客户端不同请求，给客户端发送不同的回执
	 * 
	 * @param infor请求信息
	 */
	private void handlerInformation(String infor[]) {
		if (infor == null)
			return;
		int state = -1;
		System.out.println("java_JDBC" + java_JDBC);
		if (infor.length >= 1 && java_JDBC != null) {
			if (infor[0].equals("login")) {
				state = java_JDBC.studentLogin(infor[1], infor[2],Config.className);
				System.out.println("学生登陆状态：" + state);
			} else if (infor[0].equals("sign")) {
				System.out.println("学生签到状态");
				if(Config.isSign) {
					state = java_JDBC.studentSign(infor[1], infor[2],Config.className);
					Config.signNumber = java_JDBC.searchSignCount(Config.className);
				}else {
					state = 22;
				}
			}else if(infor[0].equals("answer")) {
				if(Config.isAnswer) {
					System.out.println("infor的值哈哈哈："+infor[0]+infor[1]+infor[2]+infor[3]);
					state = java_JDBC.answerQuestion(infor[1], infor[2], infor[3], Config.className, Config.paperName);
				}else {
					state = 32;
				}
			}
		}
		writer.println(state);
	}

}
